//
//  IMSDKStartupConfigManager.m
//  DualMediationSDK
//
//  SDK启动配置管理器实现
//  Created by YeJary on 2025/7/15.
//

#import "IMSDKStartupConfigManager.h"
#import "../../Utils/Logger/IMLogUtils.h"

// 配置存储键名常量
static NSString * const kIMSDKConfigLogEnabled = @"IMSDKConfig_LogEnabled";
static NSString * const kIMSDKConfigNewUserDay = @"IMSDKConfig_NewUserDay";
static NSString * const kIMSDKConfigUserSwitchEnabled = @"IMSDKConfig_UserSwitchEnabled";
static NSString * const kIMSDKConfigUSPrivacyEnabled = @"IMSDKConfig_USPrivacyEnabled";
static NSString * const kIMSDKConfigAdjustEvent = @"IMSDKConfig_AdjustEvent";
static NSString * const kIMSDKConfigSDKType = @"IMSDKConfig_SDKType";
static NSString * const kIMSDKConfigAdTrackEnabled = @"IMSDKConfig_AdTrackEnabled";
static NSString * const kIMSDKConfigAdLoadTrackEnabled = @"IMSDKConfig_AdLoadTrackEnabled";
static NSString * const kIMSDKConfigFacebookControl = @"IMSDKConfig_FacebookControl";
static NSString * const kIMSDKConfigFacebookLevelEvent = @"IMSDKConfig_FacebookLevelEvent";

// 默认配置值
static const BOOL kDefaultLogEnabled = YES;
static const NSInteger kDefaultNewUserDay = 0;
static const BOOL kDefaultUserSwitchEnabled = NO;
static const BOOL kDefaultUSPrivacyEnabled = NO;
static NSString * const kDefaultSDKType = @"IS&MAX";
static const BOOL kDefaultAdTrackEnabled = YES;
static const BOOL kDefaultAdLoadTrackEnabled = YES;
static NSString * const kDefaultFacebookControl = @"0;2;100";

@interface IMSDKStartupConfigManager ()

@property (nonatomic, strong) NSUserDefaults *userDefaults;
@property (nonatomic, strong) dispatch_queue_t configQueue;

@end

@implementation IMSDKStartupConfigManager

#pragma mark - 单例模式

+ (instancetype)sharedManager {
    static IMSDKStartupConfigManager *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _userDefaults = [NSUserDefaults standardUserDefaults];
        _configQueue = dispatch_queue_create("com.dualmediationsdk.config", DISPATCH_QUEUE_SERIAL);
        
        // 初始化默认配置
        [self initializeDefaultConfigurationIfNeeded];
    }
    return self;
}

#pragma mark - 私有方法

/**
 * 初始化默认配置（仅在首次启动时）
 */
- (void)initializeDefaultConfigurationIfNeeded {
    // 检查是否已经初始化过
    if (![self.userDefaults objectForKey:@"IMSDKConfig_Initialized"]) {
        [self resetToDefaultConfiguration];
        [self.userDefaults setBool:YES forKey:@"IMSDKConfig_Initialized"];
        [self.userDefaults synchronize];
        
        [IMLogUtils info:IMLogTagSDKInit format:@"[IMSDKStartupConfigManager] 初始化默认配置完成"];
    }
}

/**
 * 安全地保存配置到UserDefaults
 */
- (void)safelySetValue:(id)value forKey:(NSString *)key {
    dispatch_async(self.configQueue, ^{
        if (value) {
            [self.userDefaults setObject:value forKey:key];
        } else {
            [self.userDefaults removeObjectForKey:key];
        }
        [self.userDefaults synchronize];
    });
}

/**
 * 安全地从UserDefaults获取配置
 */
- (id)safelyGetValueForKey:(NSString *)key defaultValue:(id)defaultValue {
    __block id result = defaultValue;
    dispatch_sync(self.configQueue, ^{
        id value = [self.userDefaults objectForKey:key];
        if (value) {
            result = value;
        }
    });
    return result;
}

#pragma mark - 配置应用

- (void)applySDKStartupConfig:(IMSDKStartupConfig *)config {
    if (!config) {
        [IMLogUtils warning:IMLogTagSDKInit format:@"[IMSDKStartupConfigManager] 配置对象为空，应用默认配置"];
        [self applyDefaultSDKStartupConfig];
        return;
    }
    
    [IMLogUtils info:IMLogTagSDKInit format:@"[IMSDKStartupConfigManager] 开始应用SDK启动配置"];
    
    // 应用各项配置
    [self applyLogConfiguration:config.sdk_config_log];
    [self applyNewUserDayConfiguration:config.sdk_config_new_user_day];
    [self applyUserSwitchConfiguration:config.sdk_config_user_switch];
    [self applyUSPrivacyConfiguration:config.sdk_config_us_privacy];
    [self applyAdjustEventConfiguration:config.sdk_config_adjust_event];
    [self applySDKTypeConfiguration:config.sdk_config_sdk_type];
    [self applyAdTrackConfiguration:config.sdk_config_ad_track];
    [self applyAdLoadTrackConfiguration:config.sdk_config_ad_load_track];
    [self applyFacebookControlConfiguration:config.sdk_config_fb_ctl];
    [self applyFacebookLevelEventConfiguration:config.sdk_config_fb_level_event];
    
    [IMLogUtils info:IMLogTagSDKInit format:@"[IMSDKStartupConfigManager] SDK启动配置应用完成"];
}

- (void)applyDefaultSDKStartupConfig {
    [IMLogUtils info:IMLogTagSDKInit format:@"[IMSDKStartupConfigManager] 应用默认SDK启动配置"];
    
    [self applyLogConfiguration:@(kDefaultLogEnabled)];
    [self applyNewUserDayConfiguration:@(kDefaultNewUserDay)];
    [self applyUserSwitchConfiguration:@(kDefaultUserSwitchEnabled)];
    [self applyUSPrivacyConfiguration:@(kDefaultUSPrivacyEnabled)];
    [self applyAdjustEventConfiguration:nil];
    [self applySDKTypeConfiguration:kDefaultSDKType];
    [self applyAdTrackConfiguration:@(kDefaultAdTrackEnabled)];
    [self applyAdLoadTrackConfiguration:@(kDefaultAdLoadTrackEnabled)];
    [self applyFacebookControlConfiguration:kDefaultFacebookControl];
    [self applyFacebookLevelEventConfiguration:nil];
}

#pragma mark - 独立配置应用方法

- (void)applyLogConfiguration:(nullable NSNumber *)logEnabled {
    BOOL enabled = logEnabled ? [logEnabled boolValue] : kDefaultLogEnabled;
    
    // 应用到IMLogUtils
    if (!enabled) {
        [IMLogUtils enableLog:YES];
        [IMLogUtils info:IMLogTagSDKInit format:@"[IMSDKStartupConfigManager] 日志已开启"];
    } else {
        [IMLogUtils enableLog:YES];
        // 注意：关闭日志后这条日志可能不会显示
        NSLog(@"[IMSDKStartupConfigManager] 日志已关闭");
    }
    
    // 保存配置
    [self safelySetValue:@(enabled) forKey:kIMSDKConfigLogEnabled];
}

- (void)applyNewUserDayConfiguration:(nullable NSNumber *)newUserDay {
    NSInteger day = newUserDay ? [newUserDay integerValue] : kDefaultNewUserDay;
    
    // 保存配置
    [self safelySetValue:@(day) forKey:kIMSDKConfigNewUserDay];
    
    [IMLogUtils info:IMLogTagSDKInit format:@"[IMSDKStartupConfigManager] 新用户天数配置已设置: %ld", (long)day];
}

- (void)applyUserSwitchConfiguration:(nullable NSNumber *)userSwitchEnabled {
    BOOL enabled = userSwitchEnabled ? [userSwitchEnabled boolValue] : kDefaultUserSwitchEnabled;
    
    // 保存配置
    [self safelySetValue:@(enabled) forKey:kIMSDKConfigUserSwitchEnabled];
    
    [IMLogUtils info:IMLogTagSDKInit format:@"[IMSDKStartupConfigManager] 用户分层开关配置已设置: %@", enabled ? @"开启" : @"关闭"];
}

- (void)applyUSPrivacyConfiguration:(nullable NSNumber *)usPrivacyEnabled {
    BOOL enabled = usPrivacyEnabled ? [usPrivacyEnabled boolValue] : kDefaultUSPrivacyEnabled;
    
    // 保存配置
    [self safelySetValue:@(enabled) forKey:kIMSDKConfigUSPrivacyEnabled];
    
    [IMLogUtils info:IMLogTagSDKInit format:@"[IMSDKStartupConfigManager] 美国隐私配置已设置: %@", enabled ? @"开启" : @"关闭"];
}

- (void)applyAdjustEventConfiguration:(nullable NSString *)adjustEvent {
    // 保存配置
    [self safelySetValue:adjustEvent forKey:kIMSDKConfigAdjustEvent];
    
    if (adjustEvent && adjustEvent.length > 0) {
        [IMLogUtils info:IMLogTagSDKInit format:@"[IMSDKStartupConfigManager] Adjust事件配置已设置: %@", adjustEvent];
        
        // 解析Adjust事件配置
        NSArray *events = [adjustEvent componentsSeparatedByString:@";"];
        for (NSString *event in events) {
            NSArray *eventParts = [event componentsSeparatedByString:@":"];
            if (eventParts.count == 2) {
                NSString *eventName = eventParts[0];
                NSString *eventToken = eventParts[1];
                [IMLogUtils info:IMLogTagSDKInit format:@"[IMSDKStartupConfigManager] Adjust事件: %@ -> %@", eventName, eventToken];
            }
        }
    } else {
        [IMLogUtils info:IMLogTagSDKInit format:@"[IMSDKStartupConfigManager] Adjust事件配置已清除"];
    }
}

- (void)applySDKTypeConfiguration:(nullable NSString *)sdkType {
    NSString *type = sdkType && sdkType.length > 0 ? sdkType : kDefaultSDKType;
    
    // 验证SDK类型
    NSArray *validTypes = @[@"IS&MAX", @"IS", @"MAX"];
    if (![validTypes containsObject:type]) {
        [IMLogUtils warning:IMLogTagSDKInit format:@"[IMSDKStartupConfigManager] 无效的SDK类型: %@，使用默认值: %@", type, kDefaultSDKType];
        type = kDefaultSDKType;
    }
    
    // 保存配置
    [self safelySetValue:type forKey:kIMSDKConfigSDKType];
    
    [IMLogUtils info:IMLogTagSDKInit format:@"[IMSDKStartupConfigManager] SDK类型配置已设置: %@", sdkType];
}

- (void)applyAdTrackConfiguration:(nullable NSNumber *)adTrackEnabled {
    BOOL enabled = adTrackEnabled ? [adTrackEnabled boolValue] : kDefaultAdTrackEnabled;
    
    // 保存配置
    [self safelySetValue:@(enabled) forKey:kIMSDKConfigAdTrackEnabled];
    
    [IMLogUtils info:IMLogTagSDKInit format:@"[IMSDKStartupConfigManager] 广告行为上报配置已设置: %@", enabled ? @"开启" : @"关闭"];
}

- (void)applyAdLoadTrackConfiguration:(nullable NSNumber *)adLoadTrackEnabled {
    BOOL enabled = adLoadTrackEnabled ? [adLoadTrackEnabled boolValue] : kDefaultAdLoadTrackEnabled;
    
    // 保存配置
    [self safelySetValue:@(enabled) forKey:kIMSDKConfigAdLoadTrackEnabled];
    
    [IMLogUtils info:IMLogTagSDKInit format:@"[IMSDKStartupConfigManager] 广告加载上报配置已设置: %@", enabled ? @"开启" : @"关闭"];
}

- (void)applyFacebookControlConfiguration:(nullable NSString *)fbControl {
    NSString *control = fbControl && fbControl.length > 0 ? fbControl : kDefaultFacebookControl;
    
    // 保存配置
    [self safelySetValue:control forKey:kIMSDKConfigFacebookControl];
    
    [IMLogUtils info:IMLogTagSDKInit format:@"[IMSDKStartupConfigManager] Facebook控制配置已设置: %@", control];
    
    // 解析Facebook控制参数
    NSArray *params = [control componentsSeparatedByString:@";"];
    if (params.count >= 3) {
        NSString *switchParam = params[0];
        NSString *showCount = params[1];
        NSString *clickRate = params[2];
        [IMLogUtils info:IMLogTagSDKInit format:@"[IMSDKStartupConfigManager] Facebook控制参数 - 切换参数: %@, 展示次数: %@, 点击率: %@", switchParam, showCount, clickRate];
    }
}

- (void)applyFacebookLevelEventConfiguration:(nullable NSString *)fbLevelEvent {
    // 保存配置
    [self safelySetValue:fbLevelEvent forKey:kIMSDKConfigFacebookLevelEvent];
    
    if (fbLevelEvent && fbLevelEvent.length > 0) {
        [IMLogUtils info:IMLogTagSDKInit format:@"[IMSDKStartupConfigManager] Facebook关卡事件配置已设置: %@", fbLevelEvent];
        
        // 解析Facebook关卡事件配置
        NSArray *events = [fbLevelEvent componentsSeparatedByString:@";"];
        for (NSString *event in events) {
            NSArray *eventParts = [event componentsSeparatedByString:@":"];
            if (eventParts.count == 2) {
                NSString *eventName = eventParts[0];
                NSString *eventValue = eventParts[1];
                [IMLogUtils info:IMLogTagSDKInit format:@"[IMSDKStartupConfigManager] Facebook关卡事件: %@ -> %@", eventName, eventValue];
            }
        }
    } else {
        [IMLogUtils info:IMLogTagSDKInit format:@"[IMSDKStartupConfigManager] Facebook关卡事件配置已清除"];
    }
}

#pragma mark - 配置获取方法

- (BOOL)isLogEnabled {
    NSNumber *value = [self safelyGetValueForKey:kIMSDKConfigLogEnabled defaultValue:@(kDefaultLogEnabled)];
    return [value boolValue];
}

- (NSInteger)getNewUserDay {
    NSNumber *value = [self safelyGetValueForKey:kIMSDKConfigNewUserDay defaultValue:@(kDefaultNewUserDay)];
    return [value integerValue];
}

- (BOOL)isUserSwitchEnabled {
    NSNumber *value = [self safelyGetValueForKey:kIMSDKConfigUserSwitchEnabled defaultValue:@(kDefaultUserSwitchEnabled)];
    return [value boolValue];
}

- (BOOL)isUSPrivacyEnabled {
    NSNumber *value = [self safelyGetValueForKey:kIMSDKConfigUSPrivacyEnabled defaultValue:@(kDefaultUSPrivacyEnabled)];
    return [value boolValue];
}

- (nullable NSString *)getAdjustEventConfiguration {
    return [self safelyGetValueForKey:kIMSDKConfigAdjustEvent defaultValue:nil];
}

- (nullable NSString *)getSDKTypeConfiguration {
    return [self safelyGetValueForKey:kIMSDKConfigSDKType defaultValue:kDefaultSDKType];
}

- (BOOL)isAdTrackEnabled {
    NSNumber *value = [self safelyGetValueForKey:kIMSDKConfigAdTrackEnabled defaultValue:@(kDefaultAdTrackEnabled)];
    return [value boolValue];
}

- (BOOL)isAdLoadTrackEnabled {
    NSNumber *value = [self safelyGetValueForKey:kIMSDKConfigAdLoadTrackEnabled defaultValue:@(kDefaultAdLoadTrackEnabled)];
    return [value boolValue];
}

- (nullable NSString *)getFacebookControlConfiguration {
    return [self safelyGetValueForKey:kIMSDKConfigFacebookControl defaultValue:kDefaultFacebookControl];
}

- (nullable NSString *)getFacebookLevelEventConfiguration {
    return [self safelyGetValueForKey:kIMSDKConfigFacebookLevelEvent defaultValue:nil];
}

#pragma mark - 配置重置

- (void)resetToDefaultConfiguration {
    [IMLogUtils info:IMLogTagSDKInit format:@"[IMSDKStartupConfigManager] 重置所有配置为默认值"];
    
    dispatch_async(self.configQueue, ^{
        [self.userDefaults setBool:kDefaultLogEnabled forKey:kIMSDKConfigLogEnabled];
        [self.userDefaults setInteger:kDefaultNewUserDay forKey:kIMSDKConfigNewUserDay];
        [self.userDefaults setBool:kDefaultUserSwitchEnabled forKey:kIMSDKConfigUserSwitchEnabled];
        [self.userDefaults setBool:kDefaultUSPrivacyEnabled forKey:kIMSDKConfigUSPrivacyEnabled];
        [self.userDefaults removeObjectForKey:kIMSDKConfigAdjustEvent];
        [self.userDefaults setObject:kDefaultSDKType forKey:kIMSDKConfigSDKType];
        [self.userDefaults setBool:kDefaultAdTrackEnabled forKey:kIMSDKConfigAdTrackEnabled];
        [self.userDefaults setBool:kDefaultAdLoadTrackEnabled forKey:kIMSDKConfigAdLoadTrackEnabled];
        [self.userDefaults setObject:kDefaultFacebookControl forKey:kIMSDKConfigFacebookControl];
        [self.userDefaults removeObjectForKey:kIMSDKConfigFacebookLevelEvent];
        [self.userDefaults synchronize];
    });
    
    // 应用默认的日志配置
    if (kDefaultLogEnabled) {
        [IMLogUtils enableLog:YES];
    } else {
        [IMLogUtils enableLog:NO];
    }
}

- (void)clearConfigurationCache {
    [IMLogUtils info:IMLogTagSDKInit format:@"[IMSDKStartupConfigManager] 清除所有配置缓存"];
    
    dispatch_async(self.configQueue, ^{
        NSArray *configKeys = @[
            kIMSDKConfigLogEnabled,
            kIMSDKConfigNewUserDay,
            kIMSDKConfigUserSwitchEnabled,
            kIMSDKConfigUSPrivacyEnabled,
            kIMSDKConfigAdjustEvent,
            kIMSDKConfigSDKType,
            kIMSDKConfigAdTrackEnabled,
            kIMSDKConfigAdLoadTrackEnabled,
            kIMSDKConfigFacebookControl,
            kIMSDKConfigFacebookLevelEvent,
            @"IMSDKConfig_Initialized"
        ];
        
        for (NSString *key in configKeys) {
            [self.userDefaults removeObjectForKey:key];
        }
        [self.userDefaults synchronize];
    });
}

@end
